import appConf from '@/config/app.config.js'

export default {
  // 配置项
  config: appConf,
  // api解析
  solveAPI ({ api, config } = {}) {
    api = api || {}
    for (let action in api) {
      let section = api[action]
      section.url = this.solveUrl({url: section.url, config})
    }
    return api
  },
  // 地址解析
  solveUrl ({method, url, data, params, config} = {}) {
    config = config || this.config || {}
    url = String(url || '')
    let hasMatchOp = false
    // 开发模型下数据轻量处理
    if (/dev/.test(config.mode) && /get/i.test(method) && typeof data === 'object' && !(typeof data.append === 'function')) {
      for (let key in data) {
        if (typeof data[key] === 'object') {
          data[key] = 'Develop mode ignore'
        }
      }
    }
    // 配置规则
    let rules = [...(config.rules || []), ...(this.config?.rules || [])]
    // 适配符替换
    if (/{.+}/.test(url) && typeof data === 'object' && !(typeof data.append === 'function')) {
      hasMatchOp = true
      for (let key in data) {
        url = url.replace('{' + key + '}', encodeURIComponent(data[key]))
      }
    }
    if (!hasMatchOp && typeof data === 'object' && !(typeof data.append === 'function')) {
      let list = []
      for (let key in data) {
        list.push(key + '=' + encodeURIComponent(data[key]))
      }
      if (list.length) {
        url += (/\?/.test(url) ? /\?$/.test(url) ? '' : '&' : '?') + list.join('&')
      }
    }
    // 地址参数生成
    if (/{.+}/.test(url) && typeof params === 'object' && !(typeof params.append === 'function')) {
      hasMatchOp = true
      for (let key in params) {
        url = url.replace('{' + key + '}', encodeURIComponent(params[key]))
      }
    }
    if (!hasMatchOp && typeof params === 'object' && !(typeof params.append === 'function')) {
      let list = []
      for (let key in params) {
        list.push(key + '=' + encodeURIComponent(params[key]))
      }
      if (list.length) {
        url += (/\?/.test(url) ? /\?$/.test(url) ? '' : '&' : '?') + list.join('&')
      }
    }

    // 主机协议适配
    rules.forEach(item => {
      let key = item.key, value = item.value
      key = key === undefined ? item.rule : key
      value = value === undefined ? item.url : value
      url = url.replace('{' + key + '}', value)
    })
    if (!/^http/i.test(url)) {
      url = /\/\//.test(url) ? config.protocol + url : config.baseURL + ('/' + url).replace(/^\/+/, '/')
    }

    return url
  },
  // 服务解析
  solveService ({ api, config, $http } = {}) {
    api = api || {}
    config = config || this.config || {}
    let service = {}
    for (let action in api) {
      let section = api[action]
      let apiParams = section.params || section.query || {}
      let apiData = section.data || {}
      service[action] = (data, options) => {
        options = options || {}
        let method = options.method || section.method || 'get'
        let params = /get/i.test(method) ? Object.assign({}, apiParams, data || {}) : undefined
        data = /post|put|delete/i.test(method) ? typeof data.append === 'function' ? data : Array.isArray(data) ? data : Object.assign({}, apiData, data || {}) : undefined
        // 地址解析
        let url = options.url || section.url
        url = this.solveUrl({method, url, data, params, config})
        // 生成地址无需请求
        if (/http/.test(section.type)) {
          return Promise.resolve(url)
        }
        // 请求头
        let headers = Object.assign({}, config.headers || {}, section.headers || {})
        $http = options.$http || $http

        return $http.request({
          method: method,
          url: url,
          headers: headers,
          params: params,
          data: data
        })
      }
    }
  
    return service
  }
}
